#-*- coding:UTF-8-*-

__author__='zhaoxp'

'''
thread usage:
注意： 使用thread，当主线程退出时，它发起的其他线程将被终止（即使没有执行完毕）

使用thread的allocate_lock()方法，将会得到一个lock，lock.acquire()得到锁，lock.release()释放锁。

thread模块主要方法：
start_new_thread(function,args kwargs=None)
allocate_lock()
exit()

LockType类型锁的对象方法：
acquire(wait=None)
locked()
release()

'''

import thread
import time

def loop0():
	print("start loop0 at: "+str(time.ctime()))
	time.sleep(4)
	print("loop0 done  at: "+str(time.ctime()))
	
def loop1():
	print("start loop1 at: "+str(time.ctime()))
	time.sleep(2)
	print("loop1 done  at: "+str(time.ctime()))
	
def main1():
	print("--------------------------------------------")
	print("starting at: "+time.ctime())
	thread.start_new_thread(loop0,())
	thread.start_new_thread(loop1,())
	time.sleep(6)
	print("all DONE at: "+time.ctime())


def loop(nloop,nsec,lock):
	print("start loop "+str(nloop)+" at: "+time.ctime())
	time.sleep(nsec)
	print("loop "+str(nloop)+" done at: "+time.ctime())
	lock.release()
	
loops=[4,2]
	
def main2():
	print("Starting at "+time.ctime())
	locks=[]
	nloops=range(len(loops))
	for i in nloops:
		lock=thread.allocate_lock()
		lock.acquire()
		locks.append(lock)
		
	print("locks count = "+str(len(locks)))
	for i in nloops:
		thread.start_new_thread(loop,(i,loops[i],locks[i]))
		
	for i in nloops:
		while locks[i].locked(): pass
		
	print("all done at : "+str(time.ctime()))

if __name__=='__main__':
	#main1()
	print('^'*50)
	main2()
